import time

from selenium.webdriver.support.expected_conditions import title_is, visibility_of_element_located
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from common.Utils import QuestDriver
from selenium.webdriver.common.by import By

class QuestHomePage:
    url = ""
    driver = ""
    def __init__(self):
        self.url = "http://8.155.1.153:8081/home"
        self.driver = QuestDriver.driver
        self.driver.get(self.url)

    #确认界面可以成功访问，并确认关键元素
    def HomeSucVisit(self):
        wait = WebDriverWait(self.driver, 1)
        wait.until(title_is("首页 - 问卷考试系统"))
        url = self.driver.current_url
        assert url == "http://8.155.1.153:8081/home"
        self.driver.find_element(By.CSS_SELECTOR,"#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-page-header.ant-pro-page-container-warp-page-header.ant-pro-page-container-warp-page-header.ant-page-header-has-breadcrumb.ant-page-header-ghost > div.ant-page-header-content > div > div > div > div > div > div.avatar___3ZBop > span > img")
        self.driver.find_element(By.CSS_SELECTOR,"#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-page-header.ant-pro-page-container-warp-page-header.ant-pro-page-container-warp-page-header.ant-page-header-has-breadcrumb.ant-page-header-ghost > div.ant-page-header-content > div > div > div > div > div > div.content___1eLtZ > div.contentTitle___Yu-cR")
        self.driver.find_element(By.CSS_SELECTOR,"#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-pro-grid-content > div > div > div > div.ant-col.ant-col-xs-24.ant-col-sm-24.ant-col-md-24.ant-col-lg-24.ant-col-xl-16 > div > div")
        self.driver.find_element(By.CSS_SELECTOR,"#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-pro-grid-content > div > div > div > div.ant-col.ant-col-xs-24.ant-col-sm-24.ant-col-md-24.ant-col-lg-24.ant-col-xl-8 > div > div.ant-card-body > div")
        QuestDriver.getScreenShot()

    #列表切换功能
    def ListSwitch(self):
        wait = WebDriverWait(self.driver, 10)
        wait.until(visibility_of_element_located((By.XPATH,'//*[@id="sk-layout"]/div/div/section/div[2]/main/div/div[2]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[1]')))
        self.driver.find_element(By.XPATH,'//*[@id="sk-layout"]/div/div/section/div[2]/main/div/div[2]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[2]').click()
        time.sleep(1)
        QuestDriver.getScreenShot()
        # self.driver.find_element(By.XPATH,'//*[@id="rc-tabs-6-panel-exam"]/div/div/div/div[2]')
        # time.sleep(3)
        # wait.until(visibility_of_element_located((By.XPATH,'//*[@id="rc-tabs-6-panel-survey"]/div')))

    #快捷创建问卷按钮测试
    def CreateQuestPage(self):
        wait = WebDriverWait(self.driver, 10)
        self.driver.find_element(By.CSS_SELECTOR,"#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-pro-grid-content > div > div > div > div.ant-col.ant-col-xs-24.ant-col-sm-24.ant-col-md-24.ant-col-lg-24.ant-col-xl-8 > div > div.ant-card-body > div > a:nth-child(1)").click()
        wait.until(visibility_of_element_located((By.CSS_SELECTOR,"#editorContent > div > div > div.header > div.header-content > div.sc-aXZVg.LyTMt.title.quill-container.not-focus > div > pre > div.ql-editor > p")))
        text = self.driver.find_element(By.CSS_SELECTOR,"#editorContent > div > div > div.header > div.header-content > div.sc-aXZVg.LyTMt.title.quill-container.not-focus > div > pre > div.ql-editor > p").text
        assert text == "请输入标题"
        # time.sleep(1)
        QuestDriver.getScreenShot()
        self.driver.back()

    #快捷创建考试按钮测试
    def CreateExamPage(self):
        wait = WebDriverWait(self.driver, 10)
        self.driver.find_element(By.CSS_SELECTOR,"#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-pro-grid-content > div > div > div > div.ant-col.ant-col-xs-24.ant-col-sm-24.ant-col-md-24.ant-col-lg-24.ant-col-xl-8 > div > div.ant-card-body > div > a:nth-child(2)").click()
        wait.until(visibility_of_element_located((By.CSS_SELECTOR,"#editorContent > div > div > div.header > div.header-content > div.sc-aXZVg.LyTMt.title.quill-container.not-focus > div > pre > div.ql-editor > p")))
        text = self.driver.find_element(By.CSS_SELECTOR,"#editorContent > div > div > div.header > div.header-content > div.sc-aXZVg.LyTMt.title.quill-container.not-focus > div > pre > div.ql-editor > p").text
        assert text == "考试名称"
        QuestDriver.getScreenShot()
        self.driver.back()

    #侧边页面切换栏测试
    def SideberTest(self):
        wait = WebDriverWait(self.driver, 10)

        self.driver.find_element(By.CSS_SELECTOR,"#sk-layout > div > div > section > aside > div > div:nth-child(1) > ul > li:nth-child(2) > span").click()
        wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,".ant-breadcrumb li:nth-child(2) .ant-breadcrumb-link")))
        text2 = self.driver.find_element(By.CSS_SELECTOR,".ant-page-header-heading > div > span").text.strip()
        assert text2 == "我的项目"

        self.driver.find_element(By.CSS_SELECTOR,"#sk-layout > div > div > section > aside > div > div:nth-child(1) > ul > li:nth-child(3) > span").click()
        text3 = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,".ant-breadcrumb-link > span"))).text.strip()
        assert text3 == "我的练习"

        # self.driver.find_element(By.CSS_SELECTOR,".ant-menu-submenu-open > div > span > div").click()
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#sk-layout > div > div > section > aside > div > div:nth-child(1) > ul > li:nth-child(4)"))).click()






# import os
# import time
# import traceback
# from datetime import datetime
#
# from selenium.webdriver.common.by import By
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
#
# from common.Utils import QuestDriver
#
#
# class QuestHomePage:
#     """
#     页面对象：Home 页的若干测试方法，使用 QuestDriver.driver 作为 WebDriver 实例。
#     改动要点：
#     - 使用显式等待（WebDriverWait + expected_conditions）替代直接查找以避免 NoSuchElementException.
#     - 在发生异常时保存截图与页面源码到 debug_logs/ 以便排查。
#     - 使用更稳健的短 Selector（对于 header）并保留原有长 Selector 的备用检查。
#     """
#
#     url = ""
#     driver = None
#
#     def __init__(self):
#         self.url = "http://8.155.1.153:8081/home"
#         self.driver = QuestDriver.driver
#         # 打开页面时允许异常抛出到上层以便识别问题
#         self.driver.get(self.url)
#
#     def _ensure_dir(self, path):
#         if not os.path.isdir(path):
#             os.makedirs(path, exist_ok=True)
#
#     def dump_debug_info(self, prefix="debug"):
#         """
#         保存截图和页面源码到项目根的 debug_logs 目录，文件名带时间戳。
#         返回 (screenshot_path, source_path)
#         """
#         try:
#             base_dir = os.path.join(os.getcwd(), "debug_logs")
#             self._ensure_dir(base_dir)
#             ts = datetime.now().strftime("%Y%m%d_%H%M%S")
#             screenshot_path = os.path.join(base_dir, f"{prefix}_{ts}.png")
#             source_path = os.path.join(base_dir, f"{prefix}_{ts}.html")
#             try:
#                 self.driver.save_screenshot(screenshot_path)
#             except Exception as e:
#                 screenshot_path = None
#                 print("Failed to save screenshot:", e)
#             try:
#                 with open(source_path, "w", encoding="utf-8") as f:
#                     f.write(self.driver.page_source)
#             except Exception as e:
#                 source_path = None
#                 print("Failed to save page source:", e)
#             return screenshot_path, source_path
#         except Exception as e:
#             print("dump_debug_info failed:", e)
#             return None, None
#
#     # 确认界面可以成功访问，并确认关键元素
#     def HomeSucVisit(self):
#         wait = WebDriverWait(self.driver, 10)
#         try:
#             wait.until(EC.title_is("首页 - 问卷考试系统"))
#             url = self.driver.current_url
#             assert url == self.url, f"当前 URL 不符合预期：{url} != {self.url}"
#
#             # 使用 presence_of_element_located 等待元素存在再获取
#             selectors = [
#                 "#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-page-header.ant-pro-page-container-warp-page-header.ant-pro-page-container-warp-page-header.ant-page-header-has-breadcrumb.ant-page-header-ghost > div.ant-page-header-content > div > div > div > div > div > div.avatar___3ZBop > span > img",
#                 "#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-page-header.ant-pro-page-container-warp-page-header.ant-pro-page-container-warp-page-header.ant-page-header-has-breadcrumb.ant-page-header-ghost > div.ant-page-header-content > div > div > div > div > div > div.content___1eLtZ > div.contentTitle___Yu-cR",
#                 "#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-pro-grid-content > div > div > div > div.ant-col.ant-col-xs-24.ant-col-sm-24.ant-col-md-24.ant-col-lg-24.ant-col-xl-16 > div > div",
#                 "#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-pro-grid-content > div > div > div > div.ant-col.ant-col-xs-24.ant-col-sm-24.ant-col-md-24.ant-col-lg-24.ant-col-xl-8 > div > div.ant-card-body > div",
#             ]
#             for sel in selectors:
#                 wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, sel)))
#             # 保存截图（项目已有工具）
#             try:
#                 QuestDriver.getScreenShot()
#             except Exception:
#                 # 退回到内置 dump 以防 QuestDriver.getScreenShot 失败
#                 self.dump_debug_info(prefix="HomeSucVisit_after")
#         except Exception:
#             screenshot, source = self.dump_debug_info(prefix="HomeSucVisit_exception")
#             print("Saved debug files:", screenshot, source)
#             traceback.print_exc()
#             raise
#
#     # 列表切换功能
#     def ListSwitch(self):
#         wait = WebDriverWait(self.driver, 10)
#         try:
#             first_tab_xpath = '//*[@id="sk-layout"]/div/div/section/div[2]/main/div/div[2]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[1]'
#             second_tab_xpath = '//*[@id="sk-layout"]/div/div/section/div[2]/main/div/div[2]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[2]'
#             wait.until(EC.visibility_of_element_located((By.XPATH, first_tab_xpath)))
#             wait.until(EC.element_to_be_clickable((By.XPATH, second_tab_xpath))).click()
#             # 确认切换发生一点延时再截图
#             time.sleep(1)
#             try:
#                 QuestDriver.getScreenShot()
#             except Exception:
#                 self.dump_debug_info(prefix="ListSwitch_after")
#         except Exception:
#             screenshot, source = self.dump_debug_info(prefix="ListSwitch_exception")
#             print("Saved debug files:", screenshot, source)
#             traceback.print_exc()
#             raise
#
#     # 快捷创建问卷按钮测试
#     def CreateQuestPage(self):
#         wait = WebDriverWait(self.driver, 10)
#         try:
#             create_selector = "#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-pro-grid-content > div > div > div > div.ant-col.ant-col-xs-24.ant-col-sm-24.ant-col-md-24.ant-col-lg-24.ant-col-xl-8 > div > div.ant-card-body > div > a:nth-child(1)"
#             wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, create_selector))).click()
#             editor_selector = "#editorContent > div > div > div.header > div.header-content > div.sc-aXZVg.LyTMt.title.quill-container.not-focus > div > pre > div.ql-editor > p"
#             wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, editor_selector)))
#             text = self.driver.find_element(By.CSS_SELECTOR, editor_selector).text.strip()
#             assert text == "请输入标题", f"CreateQuestPage: 期望 '请输入标题'，但实际为 '{text}'"
#             try:
#                 QuestDriver.getScreenShot()
#             except Exception:
#                 self.dump_debug_info(prefix="CreateQuestPage_after")
#             self.driver.back()
#         except Exception:
#             screenshot, source = self.dump_debug_info(prefix="CreateQuestPage_exception")
#             print("Saved debug files:", screenshot, source)
#             traceback.print_exc()
#             raise
#
#     # 快捷创建考试按钮测试
#     def CreateExamPage(self):
#         wait = WebDriverWait(self.driver, 10)
#         try:
#             create_selector = "#sk-layout > div > div > section > div.ant-pro-layout-container > main > div > div.ant-pro-grid-content > div > div > div > div.ant-col.ant-col-xs-24.ant-col-sm-24.ant-col-md-24.ant-col-lg-24.ant-col-xl-8 > div > div.ant-card-body > div > a:nth-child(2)"
#             wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, create_selector))).click()
#             editor_selector = "#editorContent > div > div > div.header > div.header-content > div.sc-aXZVg.LyTMt.title.quill-container.not-focus > div > pre > div.ql-editor > p"
#             wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, editor_selector)))
#             text = self.driver.find_element(By.CSS_SELECTOR, editor_selector).text.strip()
#             assert text == "考试名称", f"CreateExamPage: 期望 '考试名称'，但实际为 '{text}'"
#             try:
#                 QuestDriver.getScreenShot()
#             except Exception:
#                 self.dump_debug_info(prefix="CreateExamPage_after")
#             self.driver.back()
#         except Exception:
#             screenshot, source = self.dump_debug_info(prefix="CreateExamPage_exception")
#             print("Saved debug files:", screenshot, source)
#             traceback.print_exc()
#             raise
#
#     # 侧边页面切换栏测试
#     def SideberTest(self):
#         wait = WebDriverWait(self.driver, 15)
#         try:
#             sidebar_selector = "#sk-layout > div > div > section > aside > div > div:nth-child(1) > ul > li:nth-child(2) > span"
#             # Step: 等待侧边栏项可点击后再点击（防止页面仍在渲染）
#             wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, sidebar_selector))).click()
#
#             # 打印当前 URL 与 title 以便确认是否正确导航
#             try:
#                 print("Current URL:", self.driver.current_url)
#                 print("Page title:", self.driver.title)
#             except Exception:
#                 pass
#
#             # 更稳健的等待：先等待面包屑项（可作为页面切换的信号），再等待 header 显示
#             breadcrumb_locator = (By.CSS_SELECTOR, ".ant-breadcrumb li:nth-child(2) .ant-breadcrumb-link")
#             header_locator = (By.CSS_SELECTOR, ".ant-page-header-heading span")
#
#             wait.until(EC.visibility_of_element_located(breadcrumb_locator))
#             header_el = wait.until(EC.visibility_of_element_located(header_locator))
#             text = header_el.text.strip()
#             if text != "我的项目":
#                 screenshot, source = self.dump_debug_info(prefix="SideberTest_assert")
#                 raise AssertionError(f"SideberTest: 期望标题为 '我的项目'，但实际为 '{text}'. 调试文件: {screenshot}, {source}")
#
#             # 若一切正常，保存截图作为记录
#             try:
#                 QuestDriver.getScreenShot()
#             except Exception:
#                 self.dump_debug_info(prefix="SideberTest_after")
#             print("SideberTest passed: header text is '我的项目'")
#         except Exception:
#             screenshot, source = self.dump_debug_info(prefix="SideberTest_exception")
#             print("Saved debug files:", screenshot, source)
#             traceback.print_exc()
#             raise